package com.jinxin.platform.cdacsrecord.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdacsrecord.core.mapper.JurenAcsControlRecordInfoMapper;
import com.jinxin.platform.cdacsrecord.core.mapper.JurenAcsControlUserInfoMapper;
import com.jinxin.platform.cdacsrecord.core.mapper.JurenAcsControlUserMethodMapper;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.AcsControlImageInfoDO;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.AcsControlRecordInfo;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.AcsControlUserInfoDO;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.AcsControlUserMethodDO;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.AcsControlUserInfoVO;
import com.jinxin.platform.cdacsrecord.core.service.AcsControlAsyncService;
import com.jinxin.platform.cdacsrecord.core.service.AcsControlImageInfoService;
import com.jinxin.platform.cdacsrecord.core.service.AcsControlModuleRegService;
import com.jinxin.platform.cdacsrecord.core.utils.ImageUtils;
import com.jinxin.platform.base.common.pojo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * Description: apcos-acs
 * Created by 34759 on 2020/4/16 14:30
 */
@Service
@Slf4j
//@RegBusiness(moduleKey = "doorAcs", className = "AcsModuleRegService")
public class AcsControlModuleRegServiceImpl implements AcsControlModuleRegService {

    @Resource
    private JurenAcsControlUserInfoMapper userInfoMapper;
    @Resource
    private JurenAcsControlUserMethodMapper userMethodMapper;
    @Resource
    private JurenAcsControlRecordInfoMapper recordInfoDao;
    @Autowired
    private AcsControlAsyncService asyncService;
    @Autowired
    private AcsControlImageInfoService imageInfoService;

    /**
     * 获取门禁系统人员信息 类型：提供
     * 入参: acsUID 门禁用户ID
     * 出参：AcsControlUserInfoVO 对象
     * @param param
     * @return
     */
    @Override
    public JsonResult selAcsUserInfoById(Map param){
        if (StringUtils.isEmpty(param.get("acsUID"))) {
            return JsonResult.error("门禁用户ID不能为空");
        } else {
            AcsControlUserInfoDO userInfoDO = userInfoMapper.selectByPrimaryKey( String.valueOf( param.get("acsUID") ) );
            if(userInfoDO == null ){
                return JsonResult.error("未能查到" + param.get("acsUID").toString() + "的门禁用户信息");
            }else{
                AcsControlUserInfoVO userInfoVO = new AcsControlUserInfoVO();
                BeanUtils.copyProperties(userInfoDO,userInfoVO );
                AcsControlUserMethodDO userMethodDO = new AcsControlUserMethodDO();
                userMethodDO.setUserId(String.valueOf(param.get("acsUID")));
                List<AcsControlUserMethodDO> methodDOList = userMethodMapper.selDOByInfo(userMethodDO );
                userInfoVO.setUserMethodDOList(methodDOList);
                String result = JSONObject.toJSONString(userInfoVO);
                return JsonResult.ok("操作成功！", result);
            }
        }
    }

    /**
     * 添加开门记录信息 提供的接口
     *
     * @param param
     * @return
     */
    @Override
    public JsonResult addAcsOpenDoorLogInfo(Map param) {
        log.info("addAcsOpenDoorLogInfo param:"+param.toString());
        if(StringUtils.isEmpty(param.get("deviceName") )  ){
            return JsonResult.error("设备名称不能为空");
        }
        if(StringUtils.isEmpty(param.get("deviceId") )  ){
            return JsonResult.error("设备ID不能为空");
        }
        if(StringUtils.isEmpty(param.get("deviceMainBody") )  ){
            return JsonResult.error("设备主体不能为空");
        }
        if(StringUtils.isEmpty(param.get("deviceMainBodyId") )  ){
            return JsonResult.error("设备主体ID不能为空");
        }
        if(StringUtils.isEmpty(param.get("mainBodyIdentity") )  ){
            return JsonResult.error("主体身份不能为空");
        }
        AcsControlRecordInfo recordInfo = new AcsControlRecordInfo();
        recordInfo.setRecordType("1");
        recordInfo.setCreateTime(LocalDateTime.now());
        recordInfo.setDeviceId( String.valueOf(param.get("deviceId")));
        recordInfo.setDeviceName( String.valueOf(param.get("deviceName")));
        recordInfo.setDeviceMainBody( String.valueOf(param.get("deviceMainBody")));
        recordInfo.setDeviceMainBodyId( String.valueOf(param.get("deviceMainBodyId")));
        recordInfo.setMainBodyIdentity( String.valueOf(param.get("mainBodyIdentity")));
        if(!StringUtils.isEmpty(param.get("recordInfo") )  ){
            recordInfo.setRecordInfo(String.valueOf(param.get("recordInfo")) );
        }
        recordInfoDao.insertSelective( recordInfo );
        return JsonResult.ok("操作成功！", null);
    }

    @Override
    public JsonResult addAcsCallLogInfo(Map param) {
        log.info("addAcsCallLogInfo param:"+param.toString());
        if(StringUtils.isEmpty(param.get("deviceName") )  ){
            return JsonResult.error("呼叫设备名称不能为空");
        }
        if(StringUtils.isEmpty(param.get("deviceId") )  ){
            return JsonResult.error("呼叫设备ID不能为空");
        }
        if(StringUtils.isEmpty(param.get("deviceMainBody") )  ){
            return JsonResult.error("接听设备不能为空");
        }
        if(StringUtils.isEmpty(param.get("deviceMainBodyId") )  ){
            return JsonResult.error("接听设备ID不能为空");
        }
        if(StringUtils.isEmpty(param.get("createTime") )  ){
            return JsonResult.error("呼叫不能为空");
        }
        if(StringUtils.isEmpty(param.get("listenedTime") )  ){
            return JsonResult.error("接听时间不能为空");
        }
        if(StringUtils.isEmpty(param.get("taikDuration") )  ){
            return JsonResult.error("通话时间不能为空");
        }
        AcsControlRecordInfo recordInfo = new AcsControlRecordInfo();
        recordInfo.setRecordType("2");
        recordInfo.setCreateTime(LocalDateTime.parse( String.valueOf(param.get("createTime"))));
        recordInfo.setDeviceId( String.valueOf(param.get("deviceId")));
        recordInfo.setDeviceName( String.valueOf(param.get("deviceName")));
        recordInfo.setDeviceMainBody( String.valueOf(param.get("deviceMainBody")));
        recordInfo.setDeviceMainBodyId( String.valueOf(param.get("deviceMainBodyId")));
        recordInfo.setListenedTime(LocalDateTime.parse( String.valueOf(param.get("listenedTime"))));
        recordInfo.setTaikDuration(String.valueOf(param.get("taikDuration")));
        if(!StringUtils.isEmpty(param.get("recordInfo") )  ){
            recordInfo.setRecordInfo(String.valueOf(param.get("recordInfo")) );
        }
        recordInfoDao.insertSelective( recordInfo );
        return JsonResult.ok("操作成功！", null);
    }

    @Override
    public JsonResult addAcsVisCodeLogInfo(Map param) {
        if(StringUtils.isEmpty(param.get("recordInfo") )  ){
            return JsonResult.error("随机二维码不能为空");
        }
        JsonResult checkRes = checkLogParam(param);
        if( !checkRes.getSuccess() ){
            return checkRes;
        }
        param.put("recordType","3");
        if( saveVisCodeLogInfo(param) ==1 ){
            return JsonResult.ok("操作成功！", null);
        }else{
            return JsonResult.error("保存记录失败");
        }
    }

    @Override
    public JsonResult addAcsVisNumLogInfo(Map param) {
        if(StringUtils.isEmpty(param.get("recordInfo") )  ){
            return JsonResult.error("随机数字不能为空");
        }
        JsonResult checkRes = checkLogParam(param);
        if( !checkRes.getSuccess() ){
            return checkRes;
        }
        param.put("recordType","4");
        if( saveVisCodeLogInfo(param) ==1 ){
            return JsonResult.ok("操作成功！", null);
        }else{
            return JsonResult.error("保存随机数字记录失败");
        }
    }

    @Override
    public JsonResult addAcsVisFaceLogInfo(Map param, MultipartFile file) {
        if( null == file ){
            return JsonResult.error("人脸信息不能为空");
        }
        JsonResult checkRes = checkLogParam(param);
        if( !checkRes.getSuccess() ){
            return checkRes;
        }
        //先保存压缩照片到照片表
        AcsControlImageInfoDO imageInfoDO = new AcsControlImageInfoDO();
        try {
            byte[] bytes = ImageUtils.commpressPicCycle(file.getBytes(), 50, 0.5f);
            BASE64Encoder encoder = new BASE64Encoder();
            imageInfoDO.setCreateTime(LocalDateTime.now());
            imageInfoDO.setImageInfo( encoder.encode(bytes) );
            imageInfoService.insert(imageInfoDO);
        } catch (IOException e) {
            log.error("压缩转换图片失败，",e );
            return JsonResult.error("压缩图片失败");
        }
        param.put("recordType","5");
        param.put("recordInfo",imageInfoDO.getAcsImageId());
        if( saveVisCodeLogInfo(param) ==1 ){
            //保存人脸信息后需同步给设备并到有效期时删除
            //异步通知设备照片更新信息
            asyncService.regVisitorFace2Device(param.get("operatorId")+"",imageInfoDO.getImageInfo() ,param.get("visitorName")+"");
            return JsonResult.ok("操作成功！", null);
        }else{
            return JsonResult.error("保存人脸记录失败");
        }
    }

    /**
     * 检查入参
     * @param param
     * @return
     */
    private JsonResult checkLogParam(Map param) {
        if(StringUtils.isEmpty(param.get("createTime") )  ){
            return JsonResult.error("操作时间不能为空");
        }
        if(StringUtils.isEmpty(param.get("visitorName") )  ){
            return JsonResult.error("访客姓名不能为空");
        }
        if(StringUtils.isEmpty(param.get("operatorName") )  ){
            return JsonResult.error("操作者姓名不能为空");
        }
        if(StringUtils.isEmpty(param.get("operatorId") )  ){
            return JsonResult.error("操作者ID不能为空");
        }
        if(StringUtils.isEmpty(param.get("listenedTime") )  ){
            return JsonResult.error("有效截止时间不能为空");
        }
        //判断截止日期合法性 限制在什么范围？后台是否有权限有修改有效期

        return JsonResult.ok("校验通过！", null);
    }

    private int saveVisCodeLogInfo( Map param ) {
        AcsControlRecordInfo recordInfo = JSONObject.parseObject(JSONObject.toJSONString(param),AcsControlRecordInfo.class);
        // 设置初始状态 1
        recordInfo.setState("1");
        return recordInfoDao.insertSelective( recordInfo );
    }

}
